import React, { PureComponent } from 'react';
import { connect } from 'dva';
import style from "styled-components";
import moment from 'moment';
import {Input, Button, message, DatePicker, Checkbox, Form, Modal,TreeSelect } from 'antd';
import Drawer from 'react-motion-drawer';
import { updateComSecurityAward, getComSecurityAwardById ,getTreeperBydepart} from "../../../services/api";
import PSelect from "../../../components/Pro/PSelect";

const FormItem = Form.Item;
const dateFormat = 'YYYY/MM/DD';
const { TextArea } = Input;

const config = {
    rules: [
        {
            type: 'object',
            required: false,
            message: '请选择日期!'
        }
    ]
};


@connect(state => ({ profile: state.profile }))
@Form.create()

export default class EditIncentive extends PureComponent {
    constructor(props, context) {
        super(props, context);
        this.state = {
            openEdit: this.props.visible,
            awardId: 0,
            treeData: [
                //树
                { title: "", key: "" }
              ],
            showPerId: 0,
            perIdArray:[],
            comSecurityAward: {
                awardDate: "",
                awardType: "",
                awardUnit: "",
                isPoliceAward: false,
                awardContent: "",
                awardReason: "",
                remark: "",
            },
        };
    }

    /******************************生命周期******************************/

    componentWillReceiveProps(nextProps) {
        this.setState({ openEdit: nextProps.visible });
        if (nextProps.awardId !== this.state.awardId) {
            if (nextProps.awardId === 0 || nextProps.awardId === undefined) {
                return;
            }
            this.setState({
                awardId: nextProps.awardId
            });
            this.renderDate(nextProps.awardId);
        }
    }
    componentDidMount() {
        getTreeperBydepart({}).then(
          response => {
            console.log(response, "getTreeperBydepart-response");
            this.setState({ treeData: response.data });
          },
          err => {
            console.log(err, "getTreeperBydepart-err");
          }
        );
      }

  //树形选择器改编
  handleTreeSelectChange = (value, label, extra) => {
    const lastValue = this.state.perIdArray;
    if(extra.triggerNode && extra.triggerNode.props && extra.triggerNode.props.treeType === "1"){
    console.log("部门");
      this.setState({perIdArray:lastValue});
    }else{
    this.setState({perIdArray:value}); }
  }
    renderDate = (pro) => {
        console.log('id的值',pro);
        getComSecurityAwardById({ awardId: pro }).then((data) => {
            console.log('shuju', data.data);
            console.log("comSecurityAward", data.data.comSecurityAward);
            console.log(" data.data.comSecurityAward.awardDate:::", data.data.comSecurityAward.awardDate);
            console.log("perList", data.data.perList);
            if (data.data) {
                if (data.data.comSecurityAward.isPoliceAward === "1") {
                    data.data.comSecurityAward.isPoliceAward = true;
                    console.log('获取单个奖励信息TRUE', data.data.comSecurityAward.isPoliceAward);
                } else {
                    data.data.comSecurityAward.isPoliceAward = false;
                    console.log('获取单个奖励信息FALSE', data.data.comSecurityAward.isPoliceAward);
                }
            }
            const { setFieldsValue } = this.props.form;
            //人员处理
            const perIdArray = [];
            data.data.perList && data.data.perList.map((item)=>{
            const { perId } = item;
            perIdArray.push(perId.toString());
            });
            console.log(perIdArray);
            setFieldsValue({
                awardDate: data.data.comSecurityAward.awardDate || '',
                awardType: data.data.comSecurityAward.awardType || '',
                awardUnit: data.data.comSecurityAward.awardUnit || '',
                isPoliceAward: data.data.comSecurityAward.isPoliceAward || '',
                awardContent: data.data.comSecurityAward.awardContent || '',
                awardReason: data.data.comSecurityAward.awardReason || '',
                remark: data.data.comSecurityAward.remark || '',
            });
            this.setState({
                perIdArray,
                comSecurityAward: {
                    awardDate: data.data.comSecurityAward.awardDate || '',
                    awardType: data.data.comSecurityAward.awardType || '',
                    awardUnit: data.data.comSecurityAward.awardUnit || '',
                    isPoliceAward: data.data.comSecurityAward.isPoliceAward || '',
                    awardContent: data.data.comSecurityAward.awardContent || '',
                    awardReason: data.data.comSecurityAward.awardReason || '',
                    remark: data.data.comSecurityAward.remark || '',
                },
            });
        }, (err) => {
            console.log(err);
        });
    }

    hideModal = () => {
        this.setState({
            visible: true,
        });
    }
    handleModalOk = (e) => {
        console.log(e);
        this.setState({
            visible: false,
            openEdit: false,
        });
    }
    handleModalCancel = (e) => {
        console.log(e);
        this.setState({
            visible: false,
        });
    }
    //表单提交
    handleIncentiveSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.awardId = this.state.awardId;
                values.perIdString=this.state.perIdArray;
                const rangeValue = values['awardDateSd'];
                values.awardDate = rangeValue.format('YYYY-MM-DD');
                const { isPoliceAward } = values;
                if (isPoliceAward) {
                    values.isPoliceAward = '1';
                } else {
                    values.isPoliceAward = '0';
                }
                console.log('修改表单提交内容');
                console.log(values);
                updateComSecurityAward(values).then((data) => {
                    console.log(data);
                    this.setState({ openEdit: false });
                    this.props.tableUpdate();
                }, (err1) => {
                    console.log(err1);
                });
            }
        });
    }

    render() {
        const formItemLayout = {
            labelCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 7
                }
            },
            wrapperCol: {
                xs: {
                    span: 24
                },
                sm: {
                    span: 17
                },
                md: {
                    span: 17
                }
            }
        };
        const { getFieldDecorator } = this.props.form;
        return (
            <Content>
                {/*奖励详情*/}
                < Drawer
                    overlayColor="rgba(0, 0, 0,0)"
                    right
                    open={this.state.openEdit}
                    noTouchClose
                    width={600}
                    zIndex={2}
                    className="drawer-box"
                    onChange={(openEdit) => {
                        this.props.onChange(openEdit);
                        this.setState({ openEdit });
                    }}
                >
                    <div className="drawer">
                        <div className="drawer-header">奖励详情</div>
                        <div className="drawer-content">
                            <Form style={{ marginTop: 24 }} onSubmit={this.handleIncentiveSubmit}>
                            {this.state.showPerId === 1 ?
                                <Formitem style={{ marginLeft: 50,marginBottom:0, 'display': 'inline-block' }}>
                                <Formlable >
                                <span style={{ color: '#f5222d' }}>* </span>&nbsp;被表彰奖励人员:</Formlable>
                                <TreeSelect
                                value={this.state.perIdArray}
                                style={{
                                    width: 294,
                                    border: '1px solid #f5222d',
                                    borderRadius: 4
                                }}
                                dropdownStyle={{
                                    maxHeight: 400,
                                    overflow: "auto"
                                }}
                                treeData={this.state.treeData}
                                onChange={this.handleTreeSelectChange}
                                treeDefaultExpandAll
                                multiple
                                /> 
                                <div style={{ 'color': '#f5222d', marginLeft: 114 }}> 请选择奖励人员</div>
                                </Formitem>
                                :
                                <Formitem style={{ marginLeft: 50,marginBottom:24, 'display': 'inline-block' }}>
                                <Formlable >
                                <span style={{ color: '#f5222d' }}>* </span>&nbsp;被表彰奖励人员:</Formlable>
                                <TreeSelect
                                value={this.state.perIdArray}
                                style={{
                                    width: 294,
                                }}
                                dropdownStyle={{
                                    maxHeight: 400,
                                    overflow: "auto"
                                }}
                                treeData={this.state.treeData}
                                onChange={this.handleTreeSelectChange}
                                treeDefaultExpandAll
                                multiple
                                /> 
                                <div/>
                                </Formitem>} 
                                <FormItem {...formItemLayout} label="表彰日期">
                                {getFieldDecorator('awardDateSd', {
                                    initialValue: moment(this.state.comSecurityAward.awardDate, dateFormat),
                                    rules: [
                                        {
                                            required: true, message: '请选择表彰日期'
                                        }
                                    ]
                                }, config)(<DatePicker style={{ width: 294 }} />)}
                            </FormItem>
                                <FormItem {...formItemLayout} label="表彰类型">
                                    {getFieldDecorator('awardType', {
                                        initialValue: this.state.comSecurityAward.awardType,
                                        rules: [
                                            {
                                                required: true, message: '请选择表彰类型'
                                            }
                                        ]
                                    })(<PSelect type="awardType"  style={{ width: 294 }} />)}
                                </FormItem>
                                <FormItem {...formItemLayout} label="做出表彰奖励单位">
                                    {getFieldDecorator('awardUnit', {
                                        initialValue: this.state.comSecurityAward.awardUnit,
                                        rules: [
                                            {
                                                required: true, message: '请填写做出表彰奖励单位'
                                            }
                                        ]
                                    })(<Input style={{ width: 294 }} maxLength="50" placeholder="请输入" />)}
                                </FormItem>

                                <FormItem {...formItemLayout} label="公安机关给予表彰奖励">
                                    {getFieldDecorator('isPoliceAward', {
                                        valuePropName: 'checked',
                                        initialValue: this.state.comSecurityAward.isPoliceAward,
                                    })(<Checkbox
                                        style={{ width: 294 }}
                                    />
                                        )}
                                </FormItem>


                                <FormItem {...formItemLayout} label="表彰奖励内容">
                                    {getFieldDecorator('awardContent', {
                                        initialValue: this.state.comSecurityAward.awardContent,
                                        rules: [
                                            {
                                                required: true, message: '请填写表彰奖励内容'
                                            }
                                        ]
                                    })(<TextArea style={{ width: 294 }} maxLength="500" rows={4} placeholder="请输入" />)}
                                </FormItem>
                                <FormItem {...formItemLayout} label="表彰奖励原因">
                                    {getFieldDecorator('awardReason', {
                                        initialValue: this.state.comSecurityAward.awardReason,
                                        rules: [
                                            {
                                                required: true, message: '请填写表彰奖励原因'
                                            }
                                        ]
                                    })(<TextArea style={{ width: 294 }} maxLength="500" rows={4} placeholder="请输入" />)}
                                </FormItem>
                                <FormItem {...formItemLayout} label="备注">
                                    {getFieldDecorator('remark', {
                                        initialValue: this.state.comSecurityAward.remark,
                                    })(<TextArea style={{ width: 294 }} maxLength="500" rows={4} placeholder="请输入" />)}
                                </FormItem>
                            </Form>
                        </div>
                        <div className="drawer-footer">
                            <Button onClick={this.hideModal}>返回</Button>
                            <Button type="primary" onClick={this.handleIncentiveSubmit}>提交</Button>
                        </div>
                    </div>
                </Drawer >
                <Modal
                    title="提示"
                    visible={this.state.visible}
                    onOk={this.handleModalOk}
                    onCancel={this.handleModalCancel}
                >
                    <p>返回会取消您已填写的内容，确定返回？</p>
                </Modal>
            </Content >
        );
    }
}

/************************样式************************/

const Content = style.div`{
  font-size: 14px;
  color: rgba(0,0,0,0.65);
  .searchpanel{
     margin-bottom:16px;
    .post{
      margin:0 8px 0 16px;
    }
  }
  .btns{
    margin-top:16px;
  }
}`;
const Formitem=style.label`{

    font-family: "Monospaced Number", "Chinese Quote", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 14px;
    line-height: 1.5;
    color: rgba(0, 0, 0, 0.65);
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    list-style: none;
    vertical-align: top;
    -webkit-transition: margin 0.15s steps(1);
    transition: margin 0.15s steps(1);
  }`;
  const Formlable=style.span`{
    text-align: right;
    vertical-align: middle;
    line-height: 39.9999px;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
    margin-right:8px;

  }`;

